package com.tailyou.hms.firstapp.act;

import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.content.ContextCompat;

import com.tailyou.hms.firstapp.R;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;

public class AsyncActivity extends AppCompatActivity {

    private ProgressBar progressBar;
    private TextView tvLoadStatus;
    private Button btnDownload;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_async);
        // 找到UI控件
        progressBar = findViewById(R.id.progressBar);
        tvLoadStatus = findViewById(R.id.tvLoadStatus);
        btnDownload = findViewById(R.id.btnDownload);
        btnDownload.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                // 点击下载按钮，开始下载文件
                DownloadAsyncTask downloadAsyncTask = new DownloadAsyncTask();
                downloadAsyncTask.execute("https://api.worldskills.org/resources/download/12481/14919/15847?l=en");
            }
        });
    }

    private class DownloadAsyncTask extends AsyncTask<String, Integer, Boolean> {

        @Override
        protected Boolean doInBackground(String... strings) {
            // 后台执行下载任务
            if (strings != null && strings.length > 0) {
                String pdfUrl = strings[0];
                try {
                    URL url = new URL(pdfUrl);
                    URLConnection urlConnection = url.openConnection();
                    InputStream inputStream = urlConnection.getInputStream();
                    File externalFilesDir = ContextCompat.getExternalFilesDirs(AsyncActivity.this, Environment.DIRECTORY_DOWNLOADS)[0];
                    File file = new File(externalFilesDir, "test.pdf");
                    if (file.exists()) {
                        if (!file.delete()) {
                            return false;
                        }
                    }
                    int downloadSize = 0;
                    byte[] bytes = new byte[1024];
                    int length;
                    OutputStream outputStream = new FileOutputStream(file);
                    while ((length = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, length);
                        downloadSize += length;
                        int percent = 100 * downloadSize / 801081;
                        publishProgress(percent);
                    }
                    inputStream.close();
                    outputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    return false;
                }
            } else {
                return false;
            }
            return true;
        }

        /**
         * 任务执行前，相关设置
         */
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            tvLoadStatus.setText("下载中...");
            btnDownload.setEnabled(false);
            progressBar.setProgress(0);
        }

        /**
         * 任务执行完成后，相关设置
         *
         * @param aBoolean
         */
        @Override
        protected void onPostExecute(Boolean aBoolean) {
            super.onPostExecute(aBoolean);
            btnDownload.setText("下载完成");
            tvLoadStatus.setText(aBoolean ? "下载成功" : "下载失败");
        }

        /**
         * 任务执行过程中，更新进度
         *
         * @param values
         */
        @Override
        protected void onProgressUpdate(Integer... values) {
            super.onProgressUpdate(values);
            if (values != null && values.length > 0) {
                progressBar.setProgress(values[0]);
            }
        }
    }

}